#include <scn.h>

#include <visual.h>
#include <utils.h>
#include <debug.h>

#include <stdio.h>
#include <unistd.h>

/**
 * DESC: Load scene and display every slice from the front to back.
 *
 * IMP: HIGH
 */

int main( int argc, char *argv[] )
{
  debug_level = DEBUG_ERR;

  long sleep_us = 0;

  if ( getenv( "SLEEP" ) )
    sleep_us = atol( getenv( "SLEEP" ) );

  char *filename;
  if ( argc >= 2 )
    filename = argv[ 1 ];
  else
    filename = "/tmp/RM-cabeca.scn";

  model3d_t *m = scn_load( filename );

  surface_t *surface = surface_new( m->size.x, m->size.y );
  coord_t p0 = { 0, 0 };
  uint16_t x, y, z;

  uint16_t vmax = 0;

  for ( x=0; x < m->size.x; x++ )
    for ( y=0; y < m->size.y; y++ )
      for ( z=0; z < m->size.z; z++ )
	{
	  uint16_t v = VOXEL_AT( m, x, y, z );
	  vmax = max( vmax, v );
	}

  verbose( "Max intensity: %u\n", vmax );

  visual_init( m->size.x, m->size.y );

  for ( z=0; z < m->size.z; z++ )
    {
      surface_clear( surface );
      for ( x=0; x < m->size.x; x++ )
	for ( y=0; y < m->size.y; y++ )
	  {
	    uint16_t d = VOXEL_AT( m, x, y, z );
	    uint8_t v = 255 * ((float)d) / vmax;
	    color_t c = { v, v, v };
	    PIXEL_AT( surface, x, y ) = c;
	  }
      verbose( "%d/%d\n", z, m->size.z );

      visual_display( surface, p0 );
      visual_update();
      usleep( sleep_us );
    }

  model3d_free( m );

  visual_quit();

  return 0;
}
